use phf_codegen::Map;

use std::{
    env,
    error::Error,
    fs::File,
    io::{BufRead, BufReader, BufWriter, Write},
    path::PathBuf,
};

use brotli_decompressor::Decompressor;

// Use longer literals for better buffering
macro_rules! lit_lines {
    ($($str:literal)* $(,)?) => {{
        concat!($($str, "\n"),* ).as_bytes()
    }};
}

fn main() -> Result<(), Box<dyn Error>> {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=data/lunar");

    let input = BufReader::new(Decompressor::new(File::open("data/lunar")?, 4096));

    let path = PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("lunar_new_years.rs");

    let mut map_builder = Map::<u16>::new();

    for ele in input.lines() {
        let line = ele?;
        let (year, date) = line.split_once('\t').unwrap();
        map_builder.entry(year.parse()?, date);
    }

    let mut lunar_new_years_output = BufWriter::new(File::create(&path)?);
    lunar_new_years_output.write_all(lit_lines!(
        "// This file is auto-generated by build.rs"
        "mod lunar {"
        "    use phf::Map;"
    ))?;
    writeln!(
        lunar_new_years_output,
        "    pub static LUNAR_NEW_YEARS: Map<u16, (u16, u16)> = {};",
        map_builder.build()
    )?;

    lunar_new_years_output.write_all(lit_lines!(
        "}"
        ""
        "pub use lunar::LUNAR_NEW_YEARS;"
    ))?;

    Ok(())
}
